package com.example.netty.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * 请描述当前类的作用
 *
 * @author LSQ
 * @since 2023/2/26 14:58
 */
@ChannelHandler.Sharable //标记该类的实例可以被多个Channel共享
public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    /**
     * 当被通知Channel是活跃的时候 发送一条消息
     *
     * @param ctx
     * @author LSQ
     * @since 2023/2/26 15:01
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!!", CharsetUtil.UTF_8));
    }

    /**
     * 读取Channel中传来的数据
     *
     * @param channelHandlerContext
     * @param byteBuf
     * @author LSQ
     * @since 2023/2/26 15:02
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("Client received: " + byteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 发生异常时的触发事件
     *
     * @param ctx
     * @param cause
     * @author LSQ
     * @since 2023/2/26 15:03
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
